<template>
  <div class="page-main layout-lr page-lionbay">
    <div class="app-container" style="height:100%;width:100%;">
      <div class="flex-wrap" style="height:100%;width:100%;">
        <div class="content-wrap" v-loading="loading" style="height:100%;width:100%;">
          <map-box ref="mapBox" @load="initMap" />
          <template v-if="hadSearch">
            <div class="notice">点击地图进行拾点分析</div>
            <div class="tips">
              <div class="hd">{{ tips.title }}</div>
              <div class="bd">
                <img :src="tips.img" height="26" width="100%" />
              </div>
              <div class="ft">
                <span v-for="(item,index) in tips.value" :key="index">{{ item }}</span>
              </div>
            </div>
          </template>
          <el-popover
            class="popover-layers"
            placement="bottom-end"
            width="220"
            trigger="hover">
            <el-button slot="reference">Layers <i class="el-icon-arrow-down el-icon--right"></i></el-button>
              <template v-if="hadSearch">
                <div class="flex-block">
                  <el-checkbox  v-model="layers.locations" @change="changeLayers($event,'locations-layer')"> 验证点位 </el-checkbox>
                  <el-slider class="fr wd-80" v-model="opacity.locations" :show-tooltip="false" @change="changeOpacity($event, 'locations-layer', 'circle-opacity')"></el-slider>
                </div>
                <div class="flex-block">
                  <el-checkbox  v-model="layers.tile" @change="changeLayers($event,'tile-layer', 'raster-opacity')"> {{layers.tag}} </el-checkbox>
                  <el-slider class="fr wd-80" v-model="opacity.tile" :show-tooltip="false" @change="changeOpacity($event, 'tile-layer', 'raster-opacity')"></el-slider>
                </div>
              </template>
              <div class="flex-block">
                <el-checkbox v-model="layers.border" @change="changeLayers($event,'area-border')"> 狮子洋区域 </el-checkbox>
                <el-slider class="fr wd-80" v-model="opacity.border" :show-tooltip="false" @change="changeOpacity($event, 'area-border', 'line-opacity')"></el-slider>
              </div>
          </el-popover>
        </div>
        <div class="form-search" v-show="isSearch">
          <h3>查询条件</h3>
          <el-form size="small" :model="searchForm" label-width="90px" label-position="top">
            <el-form-item label="水质指标：">
              <el-select v-model="searchForm.tag" placeholder="请选择" style="width:100%;" >
                  <el-option v-for="(item,index) in initData.tag" :key="index" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="研究时段：">
              <my-dateRange :start.sync="searchForm.start_date" :end.sync="searchForm.end_date" :picker-options="pickerPrediction" style="width:100%;" />
            </el-form-item>
            <el-form-item class="p-t-20">
              <el-button type="primary" size="small" @click="getLionbayTile">启动反演</el-button>
              <el-button size="small" @click="resetMap">重置图层</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <echarts-point ref="echartsPoint" @show="data => $refs.showEcharts.init(data)" />
    <echarts-region ref="echartsRegion" @show="data => $refs.showEcharts.init(data)" />
    <show-echarts ref="showEcharts" />
  </div>


</template>
<script>
import mapBox from '@/components/MapBox';
import echartsPoint from '../szy/components/echartsPoint';
import echartsRegion from '../szy/components/echartsRegion';
import showEcharts from '../szy/components/showEcharts';
import lionbay from '@/assets/geojson/lionbay';

export default {
  components:{
    echartsPoint,
    echartsRegion,
    showEcharts,
    mapBox
  },
  data() {
    return {
      map: null,
      loading: false,
      isSearch: true,
      hadSearch: false,
      searchForm:{
        tag: 'tn',
        start_date: null,
        end_date: null,
      },
      pickerPrediction:{
        disabledDate:(time) => {
          const pre = new Date('2015-06-23').getTime();
          const next = new Date().getTime();
          return time.getTime() < pre || time.getTime() > next;
        }
      },
      opacity:{
        locations: 100,
        tile: 100,
        border: 100,
      },
      layers:{
        locations: false,
        tile: false,
        border: true,
        tag: null,
      },
      initData:{
        tag:[
          {id: 'tn', name: '总氮(TN)'},
          {id: 'tp', name: '总磷(TP)'},
          {id: 'nh3_n', name: '氨氮(NH3-N)'},
          {id: 'd_o', name: '解氧(DO)'},
          {id: 'turbidity', name: '浊度(NTU)'},
          {id: 'ph', name: '酸碱度(pH)'},
          {id: 'codmn', name: '高锰酸盐指数(CODmn)'},
          {id: 'temp', name: '水温(TEMP)'},
        ]
      },
      tips:{
        title: '总氮(TN)(mg/L)',
        img: require('@/assets/images/img-color.png'),
        value: [3.4673,3.6736,3.8799],
      },
    }
  },
  created(){
    let d = this.$moment().subtract(1, 'years').format('YYYY-MM-DD');
    this.searchForm.start_date = this.$moment(d).add(1, 'd').format('YYYY-MM-DD');
    this.searchForm.end_date = this.$moment().format('YYYY-MM-DD');
    this.getToken();
  },
  methods:{
    initMap(map){
      this.map = map;
      this.addBorder();
      this.addBlock();
      this.moveOnMap();
      this.clickOnMap();
    },
    getToken(){
      let url = window.location.href;
      const regex = /[?&]([^=#]+)=([^&#]*)/g;
      const params = {};
      let match;
      while ((match = regex.exec(url))) {
        params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
      }
      localStorage.setItem('access_token', params.token);
    },
    changeLayers(val, layer){    
      if(this.map.getLayer(layer)){
        this.map.setLayoutProperty(layer, 'visibility', val ? 'visible' : 'none');
      }
    },
    changeOpacity(val, layer, type){
      if(this.map.getLayer(layer)){
        this.map.setPaintProperty(layer, type, val/100);
      }
      
    },
    addBorder(){ // 添加狮子洋区域的线图层
      if (this.map.getLayer('area-border')) {
        this.map.removeLayer('area-border');
      }
      if (this.map.getSource('area-border')) {
        this.map.removeSource('area-border')
      }
      this.map.addLayer({
        id: 'area-border',
        type: 'line',
        source: {
          type: 'geojson',
          data: lionbay
        },
        layout:{
          visibility: this.layers.border ? 'visible' : 'none'
        },
        paint: {
          'line-color': '#ff0000',
          'line-width': 1,
          'line-opacity': 1,
        }
      });   
    },
    addBlock(){ // 添加狮子洋区域的透明填充图层
      if (this.map.getLayer('area-block')) {
        this.map.removeLayer('area-block');
      }
      if (this.map.getSource('area-block')) {
        this.map.removeSource('area-block')
      }
      if (!this.map.getLayer('area-block')) {
        this.map.addLayer({
          id: 'area-block',
          type: 'fill',
          source: {
            type: 'geojson',
            data: lionbay
          },
          paint: {
            'fill-color': '#43a543',
            'fill-opacity': 0,
            // 'fill-outline-color': '#000',
          },
        }, this.map.getLayer('area-border') ? 'area-border' : undefined);
      }      
    },
    addLocations(locations){ // 添加站点图层
      const geojson = {
        type: 'FeatureCollection',
        features: [],
      };
      for (const d of locations) {
        geojson.features.push({
          type: 'Feature',
          geometry: {
            type: 'Point',
            coordinates: [d.longitude, d.latitude]
          },
          properties: d
        });
      }
      if (this.map.getLayer('locations-layer')) {
        this.map.removeLayer('locations-layer');
      }
      if (this.map.getSource('locations-layer')) {
        this.map.removeSource('locations-layer')
      }
      this.layers.locations = true;
      this.map.addLayer({
          id: 'locations-layer',
          source: {
            type: 'geojson',
            data: geojson
          },
          layout: {
            visibility: this.layers.locations ? 'visible' : 'none'
          },
          type: 'circle',
          paint: {
            'circle-color': '#000',
            'circle-stroke-color': '#000',
            'circle-stroke-width': 1,
            'circle-radius': 3,
            'circle-opacity': 1
          },
        });
    },
    addTileLayer(url){// 添加在线瓦片图层	      
      if (this.map.getLayer('tile-layer')) {
        this.map.removeLayer('tile-layer');
      }
      if (this.map.getSource('tile-source')) {
        this.map.removeSource('tile-source')
      }
      this.layers.tile = true;
      this.map.addSource('tile-source', {
          type: 'raster',
          tiles: [url], // 替换为您的在线瓦片URL
          tileSize: 256
      });
      this.map.addLayer({
          id: 'tile-layer',
          type: 'raster',
          source: 'tile-source',
          layout: {
            visibility: this.layers.tile ? 'visible' : 'none'
          },
          paint: {
            'raster-opacity': 1
          }
      }, this.map.getLayer('locations-layer') ? 'locations-layer' : undefined);      
    },
    moveOnMap(){
      if (!this.map) {
        return;
      }      
      this.map.on('mousemove', (e) => {
        if(!this.map.getLayer('tile-layer')){
          return;
        }
        const features = this.map.queryRenderedFeatures(e.point, {layers: ['area-block']});
        if(features.length > 0){
          this.map.getCanvas().style.cursor = 'crosshair'
        }
      });
      this.map.on('mouseleave', 'area-block', (e) => {
        this.map.getCanvas().style.cursor = 'default'
      });
    },
    clickOnMap(){
      if (!this.map) {
        return;
      }    
      this.map.on('click', (e) => {
        if(!this.map.getLayer('tile-layer')){
          return;
        }
        console.log(this.map.getStyle().layers);
        const features = this.map.queryRenderedFeatures(e.point, {layers: ['area-block']});
        if(features.length > 0){
          let params = {
            map_lon: e.lngLat.lng,
            map_lat: e.lngLat.lat,
            tag: this.searchForm.tag
          };
          this.$refs.echartsPoint.init(params);
        }else{
          console.log('无效区域')
        }
      });
    },    
    getLionbayTile(){
      if(!this.$verify.null(this.searchForm.start_date, '请选择研究时段')){
        return;
      }
      this.$refs.echartsPoint.handleClose();
      this.$refs.echartsRegion.handleClose();
      this.hadSearch = false;
      let str = this.$util.serialize(this.searchForm);
      this.loading = true;
      this.$request('post', '/lionbay/get_lionbay_tile'+ str, '', (data,msg) => {
        // let data = lite;
        this.tile = data;
        this.loading = false;
        this.tips.title = data.titles + data.units;
        this.tips.value = [data.vismin.toFixed(3), ((data.vismin+data.vismax)/2).toFixed(3),data.vismax.toFixed(3)];
        this.hadSearch = true;
        this.layers.tag = this.searchForm.tag.toUpperCase();
        let url = data.local_url.split('api-gee');
        this.addLocations(data.locations);
        this.addTileLayer('/api-gee' + url[1]);
        // this.addTileLayer(data.local_url);
      },msg => {this.loading = false;this.$message.error('请求失败')}, {}, 'all');
      this.getRegionSeries();
    },
    getRegionSeries(){
      this.$request('post', '/lionbay/get_region_series?tag='+ this.searchForm.tag, '', (data,msg) => {
        // let data = region;
        this.$refs.echartsRegion.init(data);
      }, msg => {this.$message.error('请求失败')}, {}, 'all');
    },
    resetMap(){
      this.$refs.echartsPoint.handleClose();
      this.$refs.echartsRegion.handleClose();
      this.hadSearch = false;
      this.searchForm.tag = 'tn';
      let d = this.$moment().subtract(1, 'years').format('YYYY-MM-DD');
      this.searchForm.start_date = this.$moment(d).add(1, 'd').format('YYYY-MM-DD');
      this.searchForm.end_date = this.$moment().format('YYYY-MM-DD');
      if (!this.map) {
        return;
      }
      if (this.map.getLayer('tile-layer')) {
        this.map.removeLayer('tile-layer');
      }
      if (this.map.getSource('tile-source')) {
        this.map.removeSource('tile-source')
      }
    },
  }
}

</script>